package DB;

import Model.Item;
import Model.Product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Tomas
 */
public class ItemManager implements IFItemManager{

    private Connection con;
    private IFProductManager productManager;

    public ItemManager(){
        con = DBConnector.getInstance().getDBConnection();
        productManager = new ProductManager();
    }
    public Item getItem(int itemId, boolean retreiveAssociations) throws IllegalArgumentException {
        String param = ""+itemId;
        return singleWhere("itemId = ?", new String[]{param}, retreiveAssociations);
    }
    public ArrayList<Item> getItems(int salesOrderId, boolean retreiveAssociations) throws IllegalArgumentException {
        String param = ""+salesOrderId;
        return multipleWhere("salesOrderId = ?",new String[]{param},retreiveAssociations);
    }
    private ArrayList<Item> multipleWhere(String whereC, String[] params, boolean assoc){
        ResultSet results;
        String query = buildQuery(whereC,"SalesOrderProduct");
        ArrayList<Item> resultList = new ArrayList<Item>();
        try{
            PreparedStatement stmt = con.prepareStatement(query);
            for(int a = 0; a < params.length; a++){
              stmt.setString(a+1, params[a]);
            }
            stmt.setQueryTimeout(5);
            results = stmt.executeQuery();
            while(results.next()){
                Item newItem = getItem(results.getInt(2), assoc);
                resultList.add(newItem);
            }
            stmt.close();

        }catch(Exception e){
            e.printStackTrace();
        }
        if(resultList.isEmpty()){
            throw new IllegalArgumentException("Item list is empty");
        }
        return resultList;
    }
     private Item singleWhere(String whereC, String[] params, boolean assoc){
        ResultSet results;
        String query = buildQuery(whereC,"item");
        Item resultItem = null;
        try{
            PreparedStatement stmt = con.prepareStatement(query);
            for(int a = 0; a < params.length; a++){
              stmt.setString(a+1, params[a]);
            }
            stmt.setQueryTimeout(5);
            results = stmt.executeQuery();
            if(results.next()){
                resultItem = buildItem(results);
                if(assoc){
                    resultItem.setProduct(productManager.getProduct(resultItem.getProduct().getProductId(), assoc));
                }
            }
            
            stmt.close();

        }catch(Exception e){
            System.out.println(e.getMessage());
        }
       if(resultItem == null){
            throw new IllegalArgumentException("Item not found");
        }
        return resultItem;
    }
    private String buildQuery(String whereC, String from){
        String query = "SELECT * FROM "+from;
        if(!whereC.isEmpty()){
            query = query+" WHERE "+whereC;
        }
        return query;
    }
    private Item buildItem(ResultSet resSet){
        Item item = null;
        try {
            item = new Item(resSet.getInt(1),new Product(resSet.getInt(2)),
                    resSet.getByte(3)==1?true:false);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return item;
    }

    public void assignItemToOrder(Item item, int salesOrderId) {
        String query = "INSERT INTO SalesOrderProduct(salesOrderId, itemId)"
                + " values(?, ?)";
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setInt(1, salesOrderId);
            stmt.setInt(2, item.getItemId());
            if(stmt.executeUpdate() == 0){
                throw new IllegalArgumentException("Item assigning failed");
            }
            stmt.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}
